import React, { useState, useEffect, useRef } from 'react'
import { Card, Breadcrumb, Form, Input, Radio, Space, Button, Upload, Modal, message } from 'antd'
import { Link, useHistory } from 'react-router-dom'
import Channel from './Channel'
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss'
import { PlusOutlined } from '@ant-design/icons'
import { baseURL } from '../../utils/request';
import { getToken } from '../../utils/storage'
import { publishArticleAPI, getArticleById, updateArticleAPI } from "../../api/user"
export default function ArticlePublish(props) {
    const [fileList, setFileList] = useState([])
    const [type, setType] = useState(0)
    const [showPreview, setShowPreview] = useState(false)
    const [previewUrl, setPreviewUrl] = useState('')
    const draftRef = useRef(false)
    const articleId = props.match.params.id;
    const formRef = useRef(null);
    // 3. 通过ref拿到Form实例，调用实例的setFieldsValue方法，回写数据
    let history = useHistory()
    const onFinish = async (values) => {

        if (type !== fileList.length) {
            return message.warn('上传的图片数量不对')
        }
        console.log(values);
        const coverImages = fileList.map((item) => {
            return item.url || item.response.data.url
        })
        const reqParams = {
            ...values,
            // 封面数据
            cover: {
                type: type,
                images: coverImages,
            },
            // 存草稿参数
            draft: draftRef.current,
        }
        if (articleId) {
            // 修改文章
            await updateArticleAPI(
                {
                    ...values,
                    cover: {
                        type: type,
                        images: coverImages,
                    },
                    id: articleId,
                    draft: draftRef.current,
                },
            )
            message.success('修改成功')
            history.push('/list')
        } else {
            console.log('发布文章的参数检查', reqParams)
            const res = await publishArticleAPI(reqParams)
            console.log(res)
            message.success('发布成功')
            history.push('/list')
        }
    }
    const uploadImages = ({ file, fileList }) => {
        setFileList(fileList)
    }
    const changeImageType = (e) => {

        setType(e.target.value)

    }
    useEffect(() => {
        console.log(type);

    }, [type])

    const handlePreview = (file) => {
        console.log(file)
        const url = file.url || file.response.data.url
        setShowPreview(true)
        setPreviewUrl(url)
    }
    const handleCancel = () => {
        setShowPreview(false)
        setPreviewUrl('')
    }
    // 上传前的校验
    const beforeUpload = (file) => {
        // console.log(file)
        // 判断图片的带下 不能超过 500k
        if (file.size >= 1024 * 800) {
            message.warn('上传的文件不能超过500kb')
            return Upload.LIST_IGNORE
        }
        if (!['image/png', 'image/jpeg'].includes(file.type)) {
            message.warn('只能上传jpg或者png的图片')
            return Upload.LIST_IGNORE
        }
        return true
    }
    const loadDataById = async (id) => {
        // 1. 封装根据id查询的接口，
        // 3. 挂载时，发起查询请求，打印出信息
        const res = await getArticleById(id);
        console.log(res, 'res');
        formRef.current.setFieldsValue({
            ...res.data,
            type: res.data.cover.type
        });
        //    console.log(92, res.data.cover.images.map((url, index) => ({ url, uid: index })));
        setType(res.data.cover.type)
        setFileList(res.data.cover.images.map((url, index) => ({ url, uid: index })));
        console.log(95, fileList);

    };
    useEffect(() => {
        loadDataById(articleId);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    return (
        <div className={styles.root}>
            <Card
                title={
                    <Breadcrumb separator=">">
                        <Breadcrumb.Item>
                            <Link to="/home">首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>{articleId ? '编辑' : '发布'}文章</Breadcrumb.Item>
                    </Breadcrumb>
                }
            >
                <Form
                    ref={formRef}
                    size='large'
                    labelCol={{ span: 4 }}
                    // 设置字段触发验证的时机
                    validateTrigger={['onBlur', 'onChange']}
                    // 提交表单且数据验证成功后回调事件
                    onFinish={onFinish}
                    initialValues={{
                        title: '',
                        channel_id: 0,
                        content: '',
                    }}
                >
                    <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入文章标题' }]}>
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item label="频道" name="channel_id" rules={[{ required: true, message: '请选择文章频道' }]}>
                        <Channel />
                    </Form.Item>
                    <Form.Item label="封面" name="type">
                        <Radio.Group onChange={changeImageType}
                        // defaultValue={type}
                        >
                            <Radio value={0}>无图</Radio>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            {/* <Radio value={-1}>自动</Radio> */}
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        {type !== 0 && (
                            <Upload
                                listType="picture-card"
                                fileList={fileList}
                                name="image"
                                action={`${baseURL}/v1_0/upload`}
                                headers={{ Authorization: `Bearer ${getToken()}` }}
                                onChange={uploadImages}
                                onPreview={handlePreview}
                                beforeUpload={beforeUpload}
                            >
                                {fileList.length < type && <PlusOutlined />}
                            </Upload>
                        )}

                    </Form.Item>
                    <Form.Item label="内容" name="content" rules={[{
                        required: true, message: '请输入文章内容', validator: (_, value) => {
                            if (value === '<p><br></p>' || !value) {
                                return Promise.reject(new Error('内容不能为空'))
                            }
                            return Promise.resolve()
                        }
                    }]}>
                        <ReactQuill theme="snow" placeholder="请输入文章内容..." />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                {articleId ? '编辑' : '发布'}文章
                                </Button>
                            <Button htmlType='submit' onClick={() => { draftRef.current = true }}>存入草稿</Button>
                        </Space>
                    </Form.Item>
                </Form>
                {/* 弹窗，用于显示预览的图片 */}
                <Modal visible={showPreview} title='图片预览' footer={null} onCancel={handleCancel}>
                    <img alt='example' style={{ width: '100%' }} src={previewUrl} />
                </Modal>
            </Card>
        </div >
    )
}
